Show Sidebar Hide Sidebar

geom_qq in ggplot2

How to make a quantile-quantile plot in ggplot2 using geom\_qq and geom\_qq\_line.

Basic geom_qq graph

A quantile-quantile graph is used to determine whether a range of numbers follows a certain distribution: the closer the data points are to being a straight line, the closer the data is to the distribution. (The default distribution is normal.) This dataset gives the daily change in the S&P 500, as well as Apple, Microsoft, IBM, and Starbucks stocks between January 2007 and February 2016.

library(plotly)
stocks <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/stockdata2.csv",
                   stringsAsFactors = FALSE)

p <- ggplot(stocks, aes(sample=change)) +
  geom_qq()

ggplotly(p)

Adding geom_qq_line

geom_qq_line provides the 45º angle against which to compare the geom_qq plot. If the two lines match, then the plot matches the distribution. The steeper parts at the ends of the plot suggest that outliers are common in the stock data than would be in a perfect normal distribution (i.e. higher kurtosis).

library(plotly)
stocks <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/stockdata2.csv",
                   stringsAsFactors = FALSE)

p <- ggplot(stocks, aes(sample=change))+
  geom_qq() + geom_qq_line()

ggplotly(p)

Comparing Multiple Distributions

We can plot the different stocks using different colours. (Size and opacity are adjusted, and the y-axis shrunk, so that the different curves can be visually distinguished.) We can see that outlier values (both positive and negative) are more common for Starbucks and Apple.

library(plotly)
stocks <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/stockdata2.csv",
                   stringsAsFactors = FALSE)

p <- ggplot(stocks, aes(sample=change))+
  geom_qq_line() + geom_qq(aes(colour=stock), alpha=0.3, size=0.1) + 
  ylim(-10,10)

ggplotly(p)

Compared to Density Plot

This is another way of comparing the different stocks: this density plot also shows that outlier values are most common for Starbucks and Apple.

library(plotly)
stocks <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/stockdata2.csv",
                   stringsAsFactors = FALSE)

p <- ggplot(stocks, aes(x=change)) +
  geom_density(aes(color=stock))

ggplotly(p)

Facetted

library(plotly)
stocks <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/stockdata2.csv",
                   stringsAsFactors = FALSE)

p <- ggplot(stocks, aes(sample=change))+
  geom_qq_line() + geom_qq(aes(colour=stock), alpha=0.3, size=0.1) +
  facet_wrap(~stock) +
  ylim(-10,10)

ggplotly(p)